package org.kamionowski.supreme.persistence.dao;

import org.apache.commons.io.FilenameUtils;
import org.kamionowski.supreme.persistence.entity.File;
import org.kamionowski.supreme.persistence.entity.Service;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;

/**
 * Created by IntelliJ IDEA.
 * User: Marcin Kamionowski
 * Date: 13.04.11
 * Time: 21:34
 */
@Repository(value = "fileDAO")
public class FileDAOJPA extends AbstractDAOJPA implements FileDAO{

    @Override
    @Transactional
    public int deleteMarkedFiles(Service service) {
        Query query = em.createNamedQuery("deleteMarkedFilesForService");
        return query.executeUpdate();
    }

    @Override
    @Transactional
    public int markFilesForService(Service service) {
        Query query = em.createNamedQuery("markFilesForService");
        return query.executeUpdate();
    }

    @Override
    @Transactional(readOnly = true)
    public File searchByServiceAndPath(Service service, String path) {
        Query query = em.createNamedQuery("selectByServiceAndPath");
        query.setParameter("dir", FilenameUtils.getPath(path));
        query.setParameter("name", FilenameUtils.getName(path));
        query.setParameter("service", service);
        return (File)query.getSingleResult();
    }

    @Override
    @Transactional
    public void insertFile(File file) {
        em.persist(file);
    }

    @Override
    @Transactional
    public void updateFile(File file) {
        em.merge(file);
    }
}
